<?php
namespace app\admin\model;
use think\Model;

class Advert extends Model
{

    protected static function init()
    {
        //添加之前的操作
        Advert::event('before_insert',function($advert){
          if($_FILES['pic']['tmp_name']){
                $file = request()->file('pic');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
                if($info){
                    $advert['pic']='/LOLforum/'.'public/static/'.'uploads/'.date('Ymd',time()).'/'.$info->getFileName();
                }
            }
      });

     Advert::event('before_update',function($advert){
      if($_FILES['pic']['tmp_name']){
            $adv=Advert::find($advert->id);
            $thumbpath=$_SERVER['DOCUMENT_ROOT'].$adv['pic'];
            if(file_exists($thumbpath)){
                @unlink($thumbpath);
            }
            $file = request()->file('pic');
           $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
            if($info){
                $advert['pic']='/LOLforum/'.'public/static/'.'uploads/'.date('Ymd',time()).'/'.$info->getFileName();
                db('advert')->where('id',$advert->data['id'])->update(['pic' => $advert['pic']]);
            }

        }
      });

        Advert::event('before_delete',function($advert){         
                $adv=Advert::find($advert->id);
                $thumbpath=$_SERVER['DOCUMENT_ROOT'].$adv['pic'];
                if(file_exists($thumbpath)){
                    @unadvert($thumbpath);
                }
        });

    }

}
